"""
同步日志器实现

提供同步方式的日志记录，适用于特殊场景
"""

import logging
from logging.handlers import TimedRotatingFileHandler
import os
import inspect
import sys
from typing import Optional, Dict, Any
from . import exceptions
from .config import (
    LOG_DIR, LOG_FILE, LOG_RETENTION_DAYS, 
    LOG_FORMAT, DATE_FORMAT, LOG_LEVELS, get_log_level, LogLevel
)
from .formatters import CleanFilenameFormatter
from .resource_manager import resource_manager

class SyncCallContextFilter(logging.Filter):
    """同步调用位置过滤器
    
    在同步模式下捕获调用位置信息
    """
    
    def filter(self, record: logging.LogRecord) -> bool:
        """捕获同步调用位置信息
        
        Args:
            record: 日志记录对象
            
        Returns:
            bool: 始终返回True
        """
        frame = inspect.currentframe()
        try:
            # 跳过过滤器本身的调用栈
            current_frame = frame.f_back.f_back
            skip_patterns = [
                'unified_logger',
                'logging',
                'threading',
                'queue'
            ]
            
            while current_frame:
                filename = current_frame.f_code.co_filename
                func_name = current_frame.f_code.co_name
                
                is_user_code = True
                for pattern in skip_patterns:
                    if pattern in filename:
                        is_user_code = False
                        break
                
                if is_user_code:
                    record.filename = os.path.basename(filename)
                    record.module = current_frame.f_globals.get('__name__', 'unknown')
                    record.lineno = current_frame.f_lineno
                    record.funcName = func_name
                    break
                    
                current_frame = current_frame.f_back
                
        finally:
            del frame
        
        return True

class SyncUnifiedLogger:
    """同步统一日志器
    
    提供同步方式的日志记录，适用于需要立即确认日志写入的场景
    """
    
    def __init__(self) -> None:
        """初始化同步日志器"""
        self._init_log_directories()
        self._configure_logger()
    
    def __del__(self) -> None:
        """清理资源
        
        确保程序退出时关闭所有文件句柄
        """
        try:
            # 关闭所有处理器
            if hasattr(self, 'logger'):
                for handler in self.logger.handlers[:]:
                    handler.close()
                    self.logger.removeHandler(handler)
                    
        except Exception:
            pass
    
    def _init_log_directories(self) -> None:
        """创建日志目录"""
        try:
            if not os.path.exists(LOG_DIR):
                os.makedirs(LOG_DIR, exist_ok=True)
        except OSError as e:
            raise exceptions.LoggerConfigError(f"无法创建日志目录: {e}")
    
    def _configure_logger(self) -> None:
        """配置同步日志器"""
        self.logger = logging.getLogger('sync_unified_logger')
        self.logger.setLevel(get_log_level())
        
        # 清除现有处理器和过滤器
        self.logger.handlers.clear()
        for f in self.logger.filters[:]:
            self.logger.removeFilter(f)
        
        # 添加同步调用位置过滤器
        context_filter = SyncCallContextFilter()
        self.logger.addFilter(context_filter)
        
        # 创建格式化器
        formatter = CleanFilenameFormatter(
            fmt=LOG_FORMAT,
            datefmt=DATE_FORMAT
        )
        
        # 文件处理器
        try:
            file_handler = TimedRotatingFileHandler(
                LOG_FILE.replace('.log', '_sync.log'),
                when='midnight',
                interval=1,
                backupCount=LOG_RETENTION_DAYS,
                encoding='utf-8'
            )
            file_handler.setFormatter(formatter)
            file_handler.suffix = "%Y-%m-%d"
            self.logger.addHandler(file_handler)
            
            # 注册到资源管理器
            resource_manager.register_handler(file_handler)
            
        except Exception as e:
            raise exceptions.LoggerConfigError(f"配置文件处理器失败: {e}")
        
        # 报警处理器
        alert_handler = logging.StreamHandler(sys.stderr)
        alert_handler.setFormatter(formatter)
        self.logger.addHandler(alert_handler)
        resource_manager.register_handler(alert_handler)
    
    def debug(self, msg: str) -> None:
        """记录DEBUG级别日志
        
        Args:
            msg: 调试消息
        """
        self.logger.debug(msg)
    
    def info(self, msg: str) -> None:
        """记录INFO级别日志
        
        Args:
            msg: 信息消息
        """
        self.logger.info(msg)
    
    def warning(self, msg: str, alert: bool = False) -> None:
        """记录WARNING级别日志
        
        Args:
            msg: 警告消息
            alert: 是否触发报警（默认False）
        """
        self.logger.warning(msg, extra={'alert': alert})
    
    def error(self, msg: str, exc_info: Optional[Exception] = None, alert: bool = True) -> None:
        """记录ERROR级别日志
        
        Args:
            msg: 错误消息
            exc_info: 异常信息（可选）
            alert: 是否触发报警（默认True）
        """
        self.logger.error(msg, exc_info=exc_info, extra={'alert': alert})
    
    def update_log_level(self, level_name: LogLevel) -> None:
        """动态更新日志级别
        
        Args:
            level_name: 日志级别名称（DEBUG, INFO, WARNING, ERROR）
            
        Raises:
            ValueError: 当日志级别无效时
        """
        level_name = level_name.upper()
        if level_name not in LOG_LEVELS:
            raise ValueError(f"无效的日志级别: {level_name}。支持的级别: {list(LOG_LEVELS.keys())}")
        
        self.logger.setLevel(LOG_LEVELS[level_name])

# 同步日志器实例
sync_logger: SyncUnifiedLogger = SyncUnifiedLogger()